from django.conf.urls.defaults import *
from django.views.generic.list import ListView
from ximport.models import UploadFile
from django.contrib.auth.decorators import login_required, permission_required
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.views.generic.edit import DeleteView, CreateView
from jrcshared.models import JrcPermission


class ListUploadFileView(ListView):
    per_page = 20
    model = UploadFile
    template_name = "ximport/uploadfiles.html"

    def get_queryset(self):
        print "Page %s..." % self.request.GET.get("page", 1)
        qs = super(ListView, self).get_queryset().order_by("-pk")

        paginator = Paginator(qs, self.per_page, 0, True)

        try:
            page = int(self.request.GET.get("page", 1))
        except ValueError:
            page = 1
            
        try:
            qs = paginator.page(page)
        except( EmptyPage, InvalidPage ):
            qs = paginator.page(paginator.num_pages)
        
        
        return qs.object_list

class DeleteUploadFileView(DeleteView):
    model = UploadFile
    template_name = "ximport/deleteuploadfile.html"
    success_url = "/ximport/"

class CreateUploadView(CreateView):
    model = UploadFile
    template_name = "ximport/createuploadfile.html"
    success_url = "/ximport/"

urlpatterns = patterns(
    "ximport.views"
    
    , (r"^$", login_required( ListUploadFileView.as_view() ))
    , (r"^(?P<page>\d+)/uploadfiles/$", login_required( ListUploadFileView.as_view() ))
    , (r"^uploadfile/(?P<pk>\d+)/delete/", permission_required(JrcPermission.IMPORT_CHANGE, "/accounts/denied/")( DeleteUploadFileView.as_view() ))
    , (r"^uploadfile/(?P<pk>\d+)/show/", "show_upload_file")
    , (r"^uploadfile/(?P<pk>\d+)/parse/$", "parse_csv_file")
    , (r"^uploadfile/(?P<pk>\d+)/import/$", "import_csv_file")
    
    , (r"^upload/(\d+)/cst/$", permission_required(JrcPermission.IMPORT_CHANGE, "/accounts/denied/")( CreateUploadView.as_view() ))
    
    #, (r"^parse/$", "parse")
#    , (r"^(?P<id>\d+)/parse/", "parse")
    , (r"^draw_candle_chart/$", "draw_candle_chart")
)
